package com.ushine.web.component.task;

import com.ushine.web.component.exception.ServiceException;
import com.ushine.web.component.exception.ServiceExceptionEnum;
import com.ushine.web.component.task.exector.AsyncDefaultTaskExecutor;
import com.ushine.web.component.task.handler.AsyncTaskConstructor;
import com.ushine.web.component.task.model.AsyncTaskInfoDO;
import com.ushine.web.component.task.service.IAsyncTaskService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @Author: yls
 * @Date: 2021/04/28 22:56
 * @Description: 异步任务管理器
 * @Version 1.0
 */
@Component
public class AsyncTaskManager<T> {

    @Resource
    AsyncDefaultTaskExecutor asyncDefaultTaskExecutor;

    @Resource
    IAsyncTaskService asyncTaskService;


    /**
     * 功能描述:
     * 〈初始化任务信息〉
     *
     * @return : com.fight.fightdatacleaning.component.task.model.TaskInfoDO
     * @author : yls
     * @date : 2021/04/28 23:11
     */
    public AsyncTaskInfoDO<T> initTask(AsyncTaskInfoDO<T> taskInfo) {
        taskInfo.setStatus(TaskStatusEnum.WAITING.getState());
        taskInfo.setStartTime(new Date());
        insertTaskInfo(taskInfo);
        return taskInfo;
    }

    /**
     * 功能描述:
     * 〈 执行任务〉
     *
     * @param taskType             任务类型
     * @param asyncTaskInfo        任务信息
     * @param asyncTaskConstructor 任务构造器
     * @return : void
     * @throws : ServiceException 服务端自定义异常
     * @author : yls
     * @date : 2022/3/8 10:49
     */
    public void submit(String taskType, AsyncTaskInfoDO<T> asyncTaskInfo, AsyncTaskConstructor asyncTaskConstructor) throws ServiceException {
        if (AsyncConstant.SYSTEM_EXECUTOR.equals(taskType)) {
            asyncDefaultTaskExecutor.executor(asyncTaskInfo, asyncTaskConstructor);
        } else if (AsyncConstant.BUSINESS_EXECUTOR.equals(taskType)) {
            asyncDefaultTaskExecutor.executorBusiness(asyncTaskInfo, asyncTaskConstructor);
        } else if (AsyncConstant.IMPORT_EXECUTOR.equals(taskType)) {
            asyncDefaultTaskExecutor.executorImport(asyncTaskInfo, asyncTaskConstructor);
        } else if (AsyncConstant.EXPORT_EXECUTOR.equals(taskType)) {
            asyncDefaultTaskExecutor.executorExport(asyncTaskInfo, asyncTaskConstructor);
        } else {
            throw new ServiceException(ServiceExceptionEnum.NOT_SUPPORT_TYPE);
        }
    }


    /**
     * 功能描述:
     * 〈添加任务信息〉
     *
     * @param taskInfo 任务信息
     * @return : void
     * @author : yls
     * @date : 2021/04/28 23:09
     */
    public void insertTaskInfo(AsyncTaskInfoDO<T> taskInfo) {
        asyncTaskService.insertAsyncTask(taskInfo);
    }

    /**
     * 功能描述:
     * 〈添加任务信息〉
     *
     * @param taskInfo 任务信息
     * @return : void
     * @author : yls
     * @date : 2021/04/28 23:09
     */
    public void updateTaskInfo(AsyncTaskInfoDO<T> taskInfo) {
        asyncTaskService.updateAsyncTask(taskInfo);
    }


}
